import { useState, useEffect, useCallback } from "react";
import { View, Text, Button } from "@tarojs/components";
import { useLoad, navigateTo, eventCenter } from "@tarojs/taro";
import "./index.scss";

export default function List() {
  console.log("List Render");
  const [count, setCount] = useState(1);

  const increment = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  useLoad(() => {
    console.log("Page loaded.");
  });

  useEffect(() => {
    // 使用全局事件总线监听一个事件
    eventCenter.on("add", () => {
      increment();
    });

    return () => {
      // 清理回调
      eventCenter.off("add");
    };
  }, [increment]);

  const goTo = (fruit) => {
    // 跳转详情
    navigateTo({
      url: `/pages/detail/index?name=${fruit}`,
      success: (res) => {
        // 获取到 通道
        const chan = res.eventChannel;

        chan.on("message", () => {
          console.log("List Message 回调");
        });
      },
    });
  };

  return (
    <View className='list'>
      <Text>List - {count}</Text>

      <Button onClick={() => goTo("Apple")}>Apple</Button>
      <Button onClick={() => goTo("Banana")}>Banana</Button>
    </View>
  );
}
